<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body" v-if="carList.length">
        <ul class="cart-list" v-for="list in carList" :key="list.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="list.isChecked" @change="changeCheck(list,$event)">
          </li>
          <li class="cart-list-con2">
            <img :src="list.imgUrl">
            <div class="item-msg">{{ list.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ list.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="updateNum(0,list)">-</a>
            <input autocomplete="off" :value="list.skuNum" class="itxt"
                   @change="updateNum(2,list,$event)"
            >
            <a href="javascript:void(0)" class="plus" @click="updateNum(1,list)">+</a>
          </li>
          <li class=" cart-list-con6">
            <span class="sum">{{ list.skuPrice * list.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click=" deleteOne(list) ">删除</a>
            <br>
          </li>
        </ul>
      </div>
      <div v-else>
        <h3>购物车空空如也~~~~~</h3>
        <h3>
          <router-link to="/">去购物吧~~~~</router-link>
        </h3>
      </div>
    </div>
    <div class="cart-tool" v-if="carList.length">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" :checked="selectAll" @change="allChoose">
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="delAll">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{ g_total }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getChangeData, getShopCarData, allSelect, deleteIndividual, deleteSelected } from '@/api/shopCart'
import { addToCart } from '@/api/detail'

export default {
  name: 'ShopCart',
  data () {
    return {
      carList: [],
      isThrottle: false
    }
  },
  async created () {
    // 获取购物车列表
    const res = await getShopCarData()
    if (res.code === 200) {
      if (res.data[0]) {
        this.carList = res.data[0].cartInfoList
      }
    }
  },
  methods: {
    // 删除选中
    delAll () {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const skuIdList = []
        this.carList.forEach(item => {
          if (item.isChecked) {
            skuIdList.push(item.skuId)
          }
        })
        const res = await deleteSelected(skuIdList)
        if (res.code === 200) {
          this.carList = this.carList.filter(item => {
            return item.isChecked !== 1
          })
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 购买数量
    async updateNum (type, list, e) {
      if (this.isThrottle) return
      let {
        skuId,
        skuNum
      } = list
      switch (type) {
        case 1:
          if (skuNum === 200) {
            this.$message.warning('最大购买数量是 200')
          } else {
            this.isThrottle = true
            const res = await addToCart(skuId, 1)
            if (res.code === 200) {
              list.skuNum = skuNum += 1
            } else {
              list.skuNum = skuNum
            }
          }
          break
        case 0:
          if (skuNum === 1) {
            this.$message.warning('最小购买数量是 1')
          } else {
            this.isThrottle = true
            const res = await addToCart(skuId, -1)
            if (res.code === 200) {
              list.skuNum = skuNum -= 1
            }
          }
          break
        case 2:

          // eslint-disable-next-line no-case-declarations
          const { value } = e.target
          // eslint-disable-next-line no-case-declarations
          const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
          // eslint-disable-next-line no-case-declarations
          const isTrue = reg.test(value)
          if (isTrue) {
            const val = value - skuNum
            const res = await addToCart(skuId, val)
            if (res.code === 200) {
              list.skuNum = Number(value)
              list.isChecked = 1
            }
          } else if (value > 200) {
            const val = 200 - skuNum
            // 发送请求
            const res = await addToCart(skuId, val)
            if (res.code === 200) {
              list.skuNum = e.target.value = 200
            } else {
              e.target.value = skuNum
            }
          } else {
            e.target.value = list.skuNum
          }
      }
      this.isThrottle = false
    },
    // 删除一个
    async deleteOne (list) {
      const res = await deleteIndividual(list.skuId)
      if (res.code === 200) {
        this.carList = this.carList.filter(item => item.skuId !== list.skuId)
      }
    },

    // 修改是否选中
    async changeCheck (skuID, e) {
      const { skuId } = skuID
      const { checked } = e.target
      const isChecked = checked ? '1' : '0'
      const res = await getChangeData(skuId, isChecked)
      if (res.code === 200) {
        this.carList.forEach(item => {
          if (item.skuId === skuId) {
            item.isChecked = +isChecked
          }
        })
      }
    },
    // 全选
    async allChoose (e) {
      const skuIdList = []
      this.carList.forEach(item => {
        if (item.isChecked === 1) {
          skuIdList.push(item.skuId)
        }
      })
      const { checked } = e.target
      const isChecked = checked ? '1' : '0'
      const res = await allSelect(skuIdList, isChecked)
      if (res.code === 200) {
        this.carList.forEach(item => {
          item.isChecked = checked
        })
      }
    }
  },
  computed: {
    // 总价
    totalPrice () {
      let total = 0
      this.carList.forEach(item => {
        if (item.isChecked === 1) {
          total += item.skuNum * item.skuPrice
        }
      })
      return total
    },
    // 选择总件数
    g_total () {
      let total = 0
      this.carList.forEach(item => {
        total += +item.skuNum
      })
      return total
    },
    // 全选
    selectAll () {
      return this.carList.every(item => {
        return item.isChecked
      })
    }
  }
}

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;

          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
</style>
